from flask import Blueprint, jsonify
from .helpers import register_api
from app.extensions import cors, csrf
from .resources.articles import ArticleAPI
from .resources.category import CategoryAPI
from .resources.token import AuthTokenAPI


bp = Blueprint('api_v1', __name__)
cors.init_app(bp)
csrf.exempt(bp)


register_api(bp, ArticleAPI, 'articles', '/articles')

category_view = CategoryAPI.as_view('categorys')
bp.add_url_rule('/categorys', defaults={'id': None}, view_func=category_view, methods=['GET'])
bp.add_url_rule('/categorys/<int:id>', view_func=category_view, methods=['GET'])

bp.add_url_rule('/oauth/token', view_func=AuthTokenAPI.as_view('token'), methods=['POST'])


@bp.errorhandler(422)
def handle_validation_error(e):
    exc = e.exc
    return jsonify(errors=exc.messages), 422


@bp.errorhandler(403)
def handle_validation2_error(e):
    return jsonify(success=False, message='权限不够')
